package com.evan.review.ipc;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.evan.review.R;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * 文件共享通信示例
 * 演示如何通过文件共享实现进程间通信
 */
public class FileSharingDemoActivity extends AppCompatActivity {

    private static final String SHARED_FILE_NAME = "shared_data.txt";
    private static final String EXT_SHARED_FILE_NAME = "ext_shared_data.txt";

    private EditText etMessage;
    private TextView tvReadContent;
    private TextView tvReadExternalContent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file_sharing_demo);

        // 初始化视图
        initViews();
        // 设置点击监听
        setupListeners();
        
        // 启动另一个进程中的Activity来读取和写入共享文件
        findViewById(R.id.btn_launch_remote).setOnClickListener(v -> {
            Intent intent = new Intent(this, RemoteProcessActivity.class);
            intent.putExtra("from_file_sharing", true);
            startActivity(intent);
        });
    }

    private void initViews() {
        etMessage = findViewById(R.id.et_message);
        tvReadContent = findViewById(R.id.tv_read_content);
        tvReadExternalContent = findViewById(R.id.tv_read_external_content);
    }

    private void setupListeners() {
        // 内部存储写入按钮
        Button btnWrite = findViewById(R.id.btn_write);
        btnWrite.setOnClickListener(v -> {
            String message = etMessage.getText().toString().trim();
            if (!message.isEmpty()) {
                writeToInternalFile(message);
            } else {
                Toast.makeText(this, "请输入要写入的内容", Toast.LENGTH_SHORT).show();
            }
        });

        // 内部存储读取按钮
        Button btnRead = findViewById(R.id.btn_read);
        btnRead.setOnClickListener(v -> readFromInternalFile());

        // 外部存储写入按钮
        Button btnWriteExternal = findViewById(R.id.btn_write_external);
        btnWriteExternal.setOnClickListener(v -> {
            String message = etMessage.getText().toString().trim();
            if (!message.isEmpty()) {
                writeToExternalFile(message);
            } else {
                Toast.makeText(this, "请输入要写入的内容", Toast.LENGTH_SHORT).show();
            }
        });

        // 外部存储读取按钮
        Button btnReadExternal = findViewById(R.id.btn_read_external);
        btnReadExternal.setOnClickListener(v -> readFromExternalFile());

        // 共享文件介绍
        findViewById(R.id.btn_file_sharing_intro).setOnClickListener(v -> showFileSharingIntroduction());
    }

    // 写入内部存储文件
    private void writeToInternalFile(String message) {
        try {
            // 添加时间戳和进程ID
            String timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(new Date());
            String pid = String.valueOf(android.os.Process.myPid());
            String content = timestamp + " [PID:" + pid + "] " + message + "\n";

            // 使用MODE_WORLD_READABLE模式，使其他进程可以读取
            FileOutputStream fos = openFileOutput(SHARED_FILE_NAME, Context.MODE_PRIVATE);
            OutputStreamWriter osw = new OutputStreamWriter(fos);
            osw.write(content);
            osw.flush();
            osw.close();
            fos.close();

            Toast.makeText(this, "内容已写入内部存储文件", Toast.LENGTH_SHORT).show();
            // 写入后立即读取，更新UI
            readFromInternalFile();
        } catch (Exception e) {
            Toast.makeText(this, "写入内部存储文件失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }

    // 从内部存储文件读取
    private void readFromInternalFile() {
        try {
            FileInputStream fis = openFileInput(SHARED_FILE_NAME);
            InputStreamReader isr = new InputStreamReader(fis);
            BufferedReader br = new BufferedReader(isr);
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line).append("\n");
            }
            br.close();
            isr.close();
            fis.close();

            if (sb.length() > 0) {
                tvReadContent.setText(sb.toString());
            } else {
                tvReadContent.setText("文件内容为空");
            }
        } catch (Exception e) {
            tvReadContent.setText("读取文件失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    // 写入外部存储文件
    private void writeToExternalFile(String message) {
        try {
            // 添加时间戳和进程ID
            String timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(new Date());
            String pid = String.valueOf(android.os.Process.myPid());
            String content = timestamp + " [PID:" + pid + "] " + message + "\n";

            // 获取外部存储目录
            File file = new File(getExternalFilesDir(null), EXT_SHARED_FILE_NAME);
            FileOutputStream fos = new FileOutputStream(file);
            OutputStreamWriter osw = new OutputStreamWriter(fos);
            osw.write(content);
            osw.flush();
            osw.close();
            fos.close();

            Toast.makeText(this, "内容已写入外部存储文件", Toast.LENGTH_SHORT).show();
            // 写入后立即读取，更新UI
            readFromExternalFile();
        } catch (Exception e) {
            Toast.makeText(this, "写入外部存储文件失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }

    // 从外部存储文件读取
    private void readFromExternalFile() {
        try {
            File file = new File(getExternalFilesDir(null), EXT_SHARED_FILE_NAME);
            if (!file.exists()) {
                tvReadExternalContent.setText("外部存储文件不存在");
                return;
            }

            FileInputStream fis = new FileInputStream(file);
            InputStreamReader isr = new InputStreamReader(fis);
            BufferedReader br = new BufferedReader(isr);
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line).append("\n");
            }
            br.close();
            isr.close();
            fis.close();

            if (sb.length() > 0) {
                tvReadExternalContent.setText(sb.toString());
            } else {
                tvReadExternalContent.setText("文件内容为空");
            }
        } catch (Exception e) {
            tvReadExternalContent.setText("读取文件失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    // 显示文件共享IPC介绍对话框
    private void showFileSharingIntroduction() {
        new androidx.appcompat.app.AlertDialog.Builder(this)
                .setTitle("文件共享通信介绍")
                .setMessage("文件共享是Android中最简单的IPC方式之一。\n\n" +
                        "使用方法：\n" +
                        "1. 进程A将数据写入文件\n" +
                        "2. 进程B读取该文件获取数据\n\n" +
                        "特点：\n" +
                        "- 实现简单，无需复杂接口定义\n" +
                        "- 适用于数据量较大的情况\n" +
                        "- 无法进行实时通信\n" +
                        "- 需要自行处理并发访问问题\n\n" +
                        "文件类型：\n" +
                        "- 内部存储：应用私有，需要特殊权限才能被其他应用访问\n" +
                        "- 外部存储：可被其他应用访问，但需要存储权限\n\n" +
                        "适用场景：\n" +
                        "- 对实时性要求不高的数据交换\n" +
                        "- 大量数据的持久化共享")
                .setPositiveButton("了解", null)
                .show();
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 每次回到页面时刷新文件内容显示
        readFromInternalFile();
        readFromExternalFile();
    }
} 